//
//  JsonStatusParser.m
//  weibo4objc
//
//  Created by fanng yuan on 12/14/10.
//  Copyright 2010 fanngyuan@sina. All rights reserved.
//

#import "JsonStatusParser.h"
#import "SBJsonParser.h"
#import "SBJsonWriter.h"
@interface JsonStatusParser (Private) 

+ (Status *) dicToStatus:(NSDictionary *) dic;
+ (User *) dicToUser:(NSDictionary *) dic;
+ (DirectMessage *) dicToDm:(NSDictionary *) dic;
+ (NSString*)timestampTotime:(time_t)createdat;

+ (time_t)getTimeValueForKey:(NSString *)stringTime defaultValue:(time_t)defaultValue;
+ (NSString*)sourceUrlConvert:(NSString*)src;
+ (NSString*)sourceConvert:(NSString*)src;
@end

@implementation JsonStatusParser

+ (NSArray *) parseToStatuses:(NSString *) statusesString{
	SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
	NSArray * array = [jsonParser objectWithString:statusesString];
	NSMutableArray * result = [[NSMutableArray alloc] init];
	for(NSDictionary * dic in array){
		[result addObject:[self dicToStatus:dic]];
	}
	[jsonParser release];
  //  [result autorelease];
	return result;
}

+ (Status *) dicToStatus:(NSDictionary *) dic {
	Status * status = [[Status alloc] init];
	[status setText:[dic objectForKey:@"text"]];
	[status setCreated_at:[self timestampTotime:[self getTimeValueForKey:[dic objectForKey:@"created_at"] defaultValue:0]]];
    [status setAid:[[dic objectForKey:@"id"] longLongValue]];
	[status setSource:[self sourceConvert:[dic objectForKey:@"source"]]];
	[status setFavorited:[[dic objectForKey:@"favorited"] boolValue]];
	[status setTruncated:[[dic objectForKey:@"truncated"] boolValue]];
	[status setIn_reply_to_status_id:[[dic objectForKey:@"in_reply_to_status_id"] longLongValue]];
	[status setIn_reply_to_user_id:[[dic objectForKey:@"in_reply_to_user_id"] intValue]];
	[status setIn_reply_to_screen_name:[dic objectForKey:@"in_reply_to_screen_name"]];
	[status setThumbnail_pic:[dic objectForKey:@"thumbnail_pic"]];
	[status setBmiddle_pic:[dic objectForKey:@"bmiddle_pic"]];
	[status setOriginal_pic:[dic objectForKey:@"original_pic"]];
	[status setLatitude:[[dic objectForKey:@"latitude"] doubleValue]];
	[status setLongitude:[[dic objectForKey:@"longitude"] doubleValue]];
	if ([dic objectForKey:@"retweeted_status"]!= nil) {
		[status setRetweeted_status:[JsonStatusParser dicToStatus:[dic objectForKey:@"retweeted_status"]]];
	}
	[status setUser:[JsonStatusParser dicToUser:[dic objectForKey:@"user"]]];
    [status autorelease];
	return status;
} 

+ (Status *) parseToStatus:(NSString *)statusString{
	SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
	NSDictionary * dic = [jsonParser objectWithString:statusString];
	Status * status = [self dicToStatus:dic];
	[jsonParser release];
	return status;	
}

+ (User *) dicToUser:(NSDictionary *) dic{
	User * user = [[User alloc] init];
	[user setUid:[[dic objectForKey:@"id"] intValue]];
	[user setScreen_name:[dic objectForKey:@"screen_name"]];
	[user setName:[dic objectForKey:@"name"]];
	[user setProvince:[dic objectForKey:@"provice"]];
	[user setCity:[dic objectForKey:@"city"]];
	[user setLocation:[dic objectForKey:@"location"]];
	[user setDescription:[dic objectForKey:@"description"]];
	[user setUrl:[dic objectForKey:@"url"]];
	[user setProfile_image_url:[dic objectForKey:@"profile_image_url"]];
	[user setDomain:[dic objectForKey:@"domain"]];
	[user setGender:[dic objectForKey:@"gender"]];
	[user setFollowers_count:[[dic objectForKey:@"followers_count"] intValue]];
	[user setFriends_count:[[dic objectForKey:@"friends_count"] intValue]];
	[user setStatuses_count:[[dic objectForKey:@"statuses_count"] intValue]];
	[user setFavourites_count:[[dic objectForKey:@"favourites_count"] intValue]];
	[user setCreated_at:[dic objectForKey:@"created_at"]];
	[user setFollowing:[[dic objectForKey:@"following"] boolValue]];
	[user setVerified:[[dic objectForKey:@"verified"] boolValue]];
	[user setAllow_all_act_msg:[[dic objectForKey:@"allow_all_act_msg"] boolValue]];
	[user setGeo_enabled:[[dic objectForKey:@"geo_enabled"] boolValue]];
	if([dic objectForKey:@"status"]!=nil)
		[user setStatus:[JsonStatusParser dicToStatus:[dic objectForKey:@"status"]]];
    [user autorelease];
	return user;
}

+ (Comment *) dicToComment:(NSDictionary *) dic{
	Comment * comment = [[Comment alloc] init];
	[comment setCreated_at:[dic objectForKey:@"created_at"]];
	[comment setAid:[[dic objectForKey:@"id"]longLongValue]];
	[comment setText:[dic objectForKey:@"text"]];
	[comment setUser:[JsonStatusParser dicToUser:[dic objectForKey:@"user"]]];
    [comment autorelease];
	return comment;
}

+ (Comment *) parseToComment:(NSString *) commentStrig{
	SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
	NSDictionary * dic = [jsonParser objectWithString:commentStrig];
	Comment * comment = [self dicToComment:dic];
	[jsonParser release];
	[dic release];
	return comment;	
}

+ (NSArray *) parseToComments:(NSString *) commentsString{
	SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
	NSArray * array = [jsonParser objectWithString:commentsString];
	NSMutableArray * result = [[NSMutableArray alloc] init];
	for(NSDictionary * dic in array){
		[result addObject:[self dicToComment:dic]];
	}
	[jsonParser release];
	[result autorelease];
	return result;
}

+ (NSArray *) parseToDms:(NSString *) dmsString{
	SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
	NSArray * array = [jsonParser objectWithString:dmsString];
	NSMutableArray * result = [[NSMutableArray alloc] init];
	for(NSDictionary * dic in array){
		[result addObject:[self dicToDm:dic]];
	}
	[jsonParser release];
	[result autorelease];
	return result;
}

+ (DirectMessage *) parseToDm:(NSString *) dmString{
	SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
	NSDictionary * dic = [jsonParser objectWithString:dmString];
	[jsonParser release];
	DirectMessage * dm = [self dicToDm:dic];
	[dic release];
	return dm;		
}

+ (DirectMessage *) dicToDm:(NSDictionary *) dic{
	DirectMessage * dm = [[DirectMessage alloc]init];
	[dm setCreated_at:[dic objectForKey:@"created_at"]];
	[dm setAid:[[dic objectForKey:@"id"] longLongValue]];
	[dm setText:[dic objectForKey:@"text"]];
	[dm setSender_id:[[dic objectForKey:@"sender_id"] longLongValue]];
	[dm setRecipient_id:[[dic objectForKey:@"recipient_id"]longLongValue]];
	[dm setSender_screen_name:[dic objectForKey:@"sender_screen_name"]];
	[dm setRecipient_screen_name:[dic objectForKey:@"recipient_screen_name"]];
	[dm setSender:[JsonStatusParser dicToUser:[dic objectForKey:@"sender"]]];
	[dm setRecipient:[JsonStatusParser dicToUser:[dic objectForKey:@"recipient"]]];
    [dm autorelease];
	return dm;		
}

+ (ServerSideError *) parsetoServerSideError:(NSString *) errorString{
	SBJsonParser * jsonParser = [[SBJsonParser alloc] init];
	NSDictionary * dic =[jsonParser objectWithString:errorString];
	ServerSideError * error = [[ServerSideError alloc] init];
	[error setRequest:[dic objectForKey:@"request"]];
	[error setError_code:[[dic objectForKey:@"error_code"] intValue]];
	[error setError:[dic objectForKey:@"error"]];
	[jsonParser release];
    [error autorelease];
	return error;
}



+ (NSArray *) parseToTencentStatuses:(NSString *) statusesString{
	SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
    SBJsonWriter *sbjsonwrite = [[SBJsonWriter alloc]init];
    //	NSError * error;
    NSString *str = [[jsonParser objectWithString:statusesString] valueForKey:@"data"];
    NSString *str2 =[sbjsonwrite stringWithFragment:str] ;
    NSArray * array = [[jsonParser objectWithString:str2]objectForKey:@"info"];
  	NSMutableArray * result = [[NSMutableArray alloc] init];
	for(NSDictionary * dic in array){
		[result addObject:[self dicToTencentStatus:dic]];
    }
	[jsonParser release];
    [sbjsonwrite release];
   // [result autorelease];
	return result;
}




+ (Status *) dicToTencentStatus:(NSDictionary *) dic {
	Status * status = [[Status alloc] init];
	[status setText:[dic objectForKey:@"text"]];
	[status setCreated_at:[self timestampTotime:[[dic objectForKey:@"timestamp"] longLongValue] ]];
   	[status setAid:[[dic objectForKey:@"id"] longLongValue]];
	[status setSource:[self sourceConvert:[dic objectForKey:@"from"]]];
	[status setIn_reply_to_screen_name:[dic objectForKey:@"nick"]];
    [status setThumbnail_pic:[self ImagerUrlConvertToUrl:[dic objectForKey:@"image"]]];
   	if ([[dic objectForKey:@"type"] intValue] ==2) {
        [status setRetweeted_status:[JsonStatusParser dicToTencentStatus:[dic objectForKey:@"source"]]];
	}
	[status setUser:[JsonStatusParser dicToTencentUser:dic]];
    [status autorelease];
	return status;
} 








+ (User *) dicToTencentUser:(NSDictionary *) dic{
	User * user = [[User alloc] init];
	
	[user setScreen_name:[dic objectForKey:@"nick"]];
	[user setName:[dic objectForKey:@"name"]];
	[user setProvince:[dic objectForKey:@"province_code"]];
	[user setCity:[dic objectForKey:@"city_code"]];
	[user setLocation:[dic objectForKey:@"location"]];
	[user setProfile_image_url:[self HeadUrlConvertToUrl:[dic objectForKey:@"head"]]];
	[user setGeo_enabled:[[dic objectForKey:@"geo"] boolValue]];
	[user autorelease];
	return user;
}

+ (DirectMessage *) dicToTencentDm:(NSDictionary *) dic{
	DirectMessage * dm = [[DirectMessage alloc]init];
	[dm setCreated_at:[dic objectForKey:@"created_at"]];
	[dm setAid:[[dic objectForKey:@"id"] longLongValue]];
	[dm setText:[dic objectForKey:@"text"]];
	[dm setSender_id:[[dic objectForKey:@"sender_id"] longLongValue]];
	[dm setRecipient_id:[[dic objectForKey:@"recipient_id"]longLongValue]];
	[dm setSender_screen_name:[dic objectForKey:@"sender_screen_name"]];
	[dm setRecipient_screen_name:[dic objectForKey:@"recipient_screen_name"]];
	[dm setSender:[JsonStatusParser dicToUser:[dic objectForKey:@"sender"]]];
	[dm setRecipient:[JsonStatusParser dicToUser:[dic objectForKey:@"recipient"]]];
    [dm autorelease];
	return dm;		
}

+ (Comment *) dicToTencentComment:(NSDictionary *) dic{
	Comment * comment = [[Comment alloc] init];
	[comment setCreated_at:[dic objectForKey:@"created_at"]];
	[comment setAid:[[dic objectForKey:@"id"]longLongValue]];
	[comment setText:[dic objectForKey:@"text"]];
	[comment setUser:[JsonStatusParser dicToUser:[dic objectForKey:@"user"]]];
    [comment autorelease];
	return comment;
}

+(NSMutableString *)HeadUrlConvertToUrl:(NSString*) url
{
    
        NSMutableString *imagerUrl = [[NSMutableString alloc]init];
    if ((NSNull*)url !=[NSNull null]) {
        [imagerUrl appendFormat:@"%@t3%@/50",[url substringToIndex:7],[url substringFromIndex:10]];
       
    }
    [imagerUrl autorelease];
     return imagerUrl;
}

+(NSMutableString *)ImagerUrlConvertToUrl:(NSString*) url
{
    
    NSMutableString *imagerUrl = [[NSMutableString alloc]init];
    if ((NSNull*)url !=[NSNull null]) {
        NSArray *array =[NSArray arrayWithObject:(NSArray*)url];
        for(int i=0;i<[array count];i++ )
        {
            NSArray *image =[array objectAtIndex:i];
            [imagerUrl appendFormat:@"%@t3%@/80",[[image objectAtIndex:i] substringToIndex:7],[[image objectAtIndex:i] substringFromIndex:10]];
        }
    }
    
    [imagerUrl autorelease];
    return imagerUrl;
        
}

+ (NSString*)timestampTotime:(time_t)createdat
{
	NSString *_timestamp;
    time_t now;
    time(&now);
    int distance = (int)difftime(now, createdat);
    if (distance < 0) distance = 0;
        static NSDateFormatter *dateFormatter = nil;
        if (dateFormatter == nil) {
            dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
            //[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:createdat];        
    _timestamp = [dateFormatter stringFromDate:date];
    return _timestamp;
}

+ (time_t)getTimeValueForKey:(NSString *)stringTime defaultValue:(time_t)defaultValue {
    if ((id)stringTime == [NSNull null]) {
        stringTime = @"";
    }
	struct tm created;
    time_t now;
    time(&now);
    
	if (stringTime) {
		if (strptime([stringTime UTF8String], "%a %b %d %H:%M:%S %z %Y", &created) == NULL) {
			strptime([stringTime UTF8String], "%a, %d %b %Y %H:%M:%S %z", &created);
		}
		return mktime(&created);
	}
	return defaultValue;
}
//
+ (NSString*)sourceConvert:(NSString*)src
{
  //  NSString *sourceUrl = nil;
    NSString *source=[NSString stringWithFormat:@""];
    NSRange r = [src rangeOfString:@"<a href"];
    NSRange end;
    if (r.location != NSNotFound) {
        NSRange start = [src rangeOfString:@"\">"];
        end   = [src rangeOfString:@"</a>"];
        if (start.location != NSNotFound && end.location != NSNotFound) {
            r.location = start.location + start.length;
            r.length = end.location - r.location;
            source = [src substringWithRange:r];
        }
        else {
            source = @"";
        }
    }
    else {
        source = src;
    }
   //NSLog(@"++++++++++%@",source);
    return source;
}
//
+ (NSString*)sourceUrlConvert:(NSString*)src
{
    NSString *sourceUrl =[NSString stringWithFormat:@""];
    NSRange r = [src rangeOfString:@"<a href"];
    NSRange end;
    if (r.location != NSNotFound) {
        NSRange start = [src rangeOfString:@"<a href=\""];
        if (start.location != NSNotFound) {
            int l = [src length];
            NSRange fromRang = NSMakeRange(start.location + start.length, l-start.length-start.location);
            end   = [src rangeOfString:@"\"" options:NSCaseInsensitiveSearch 
                                 range:fromRang];
            if (end.location != NSNotFound) {
                r.location = start.location + start.length;
                r.length = end.location - r.location;
                sourceUrl = [src substringWithRange:r];
            }
            else {
                sourceUrl = @"";
            }
        }
        else {
            sourceUrl = @"";
        }	
    }
    else
    {
        sourceUrl = @"";
    }
        return sourceUrl;
}


@end
